<?php
namespace common\bonus;
use common\bonus\Validata;
use common\models\TradeModel;
use common\models\Balance;
use common\utils\CommonFun;
use common\models\StaticInstance;
use common\models\Member;
use common\models\BalanceLog;

###分享奖励/推荐奖励/三级分销

class Recommend
{
//	public static $investArr = array(
//		'100'	=> 5,
//		'500'	=> 8,
//		'1000'	=> 10,
//	);

	public static function bonusAction($params)
	{

		$conf = TradeModel::getRecommendConf('Recommend');
		if(!$conf) return ['state'=>false,'msg'=>'参数配置有误'];

		## 帐本分配方式
		$assignType = json_decode($conf['assign_type'], 1);
		if(!$assignType || !is_array($assignType)) return ['state'=>false,'msg'=>'账本分配方式配置格式错误'];

		## 分红层数 与比例
		$bonusConf = json_decode($conf['bonus_conf'], 1);
		if(!$bonusConf || !is_array($bonusConf)) return ['state'=>false,'msg'=>'分红比例配置格式错误'];
		
		$params['member'] = Member::getMemberById($params['member_id'],['member_id','invite_id','grade','m_grade']);


		foreach($params['uper'] as $k=>$member)
		{   
		     $state = Member::getOne(['member_id'=>$member],'state');
            if ($state==0){
                continue;
            }
		    $st = mktime(0,0,0,date('m'),date('d'),date('Y'));
			if($k == 0) continue;
			if($k > $conf['bonus_layer']) return ['state'=>true,'msg'=>'ok'];
			// if($member['m_grade']<$params['member']['m_grade']) continue; 


			## 封顶限制
			$profit = BalanceLog::find()->where(['member_id' => $member['member_id'], 'balance_type' => 4, 'log_type' => 1])->andWhere(['>=', 'create_time', $st])->sum('balance');
			$staticTotal = StaticInstance::find()->where(['member_id' => $member['member_id']])->sum('in_num');

            if ($profit && $staticTotal) {
                if ($profit >= $staticTotal)  continue;
            }

			//条件验证
			$ruleData = self::getRuleData($conf,$member);

			if(!Validata::validata($ruleData)) continue;

			$bonus = self::getBonus($member,$params,$bonusConf,$conf,$k);

			if($bonus<=0) continue;

			if($conf['bonus_type'] == 2)
			{
				## 加速释放
				$where = ['member_id'=>$member['member_id'],'status'=>'1'];
				$instances = StaticInstance::find()->where($where)->asarray()->all();
				if(!$instances) continue;

				//减少静态
				$remainBonus = $bonus;
				foreach($instances as $instance)
				{
					if($remainBonus<=0) continue;
					$maxBonus = min($remainBonus,$instance['remain_num']);
					$data = array();
					$data['remain_num'] = $instance['remain_num'] - $maxBonus;
					$data['was_num'] = $instance['was_num'] + $maxBonus;
					$data['update_time'] = time();
					if($data['remain_num']<=0) $data['status'] = '2';
					if(StaticInstance::updateAll($data,['id'=>$instance['id']])){
						$remainBonus -= $maxBonus;
					}
				}
				if($remainBonus>0) $bonus = $bonus - $remainBonus;
			}


			foreach($assignType as $btype=>$rate)
			{
				$balance = round($bonus * $rate / 100 , 2);

				//加入到账本
				$res = Balance::addBalance($member['member_id'], $btype, $balance, 10, $params['source_id'], $params['desc']);
				if(!$res['state']){
					$str = '分享奖励 member:'.json_encode($member).' data:'.json_encode($params)."\r\n conf:".json_encode($conf).'msg:'.$res['msg'];
					CommonFun::writeLog($str,'bonus');
				}
			}

		}
		return ['state'=>true,'msg'=>'ok'];
	}


	## 组装条件规则数据
	protected static function getRuleData($conf,$member)
	{
		$ruleData = array();
		$ruleData['rule'] = $conf['condition'];
		$ruleData['context']['grade'] = $member['grade'];
		return $ruleData;
	}


	## 获取分红金额
	protected static function getBonus($member, $params, $bonusConf, $conf, $k)
	{

		$money = round($params['money']);

		return ($money * $params['zhitui_income']??0) / 100;

		// //按比例计算
		// if($conf['rate_type']==1)
		// {
		// 	## 有烧伤
		// 	//$money = min(self::$investArr[$member['m_grade']],self::$investArr[$params['member']['m_grade']]);

		// 	## 无烧伤
		// 	$money = $params['money'];
			
		// 	return $money*$bonusConf[$k]/100;
		// }

		// if($conf['rate_type']==2)
		// {
		// 	return $bonusConf[$k];
		// }
		// return 0;
	}
}